//
//  CZComposePictureView.swift
//  weibo
//
//  Created by Apple on 16/3/18.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

private let ComposePictureViewCellIdentifier = "CZComposePictureViewIdentifier"
class CZComposePictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {

    //  显示的图片数据源
    lazy var images: [UIImage] = [UIImage]()
    
    var addImageClosure: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        backgroundColor = RandomColor()
        //  注册cell
        registerClass(CZComposePictureViewCell.self, forCellWithReuseIdentifier: ComposePictureViewCellIdentifier)
        dataSource = self
        delegate = self
        //  默认隐藏
        hidden = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加图片
    func addImage(image: UIImage) {
        images.append(image)
        reloadData()
        //  添加图片显示
        hidden = false
    }
    
    
    //  设置每个cell的大小，在layoutsubview里面
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        //  item直接的间距
        let itemMargin: CGFloat = 5
        //  为了防止循环小数，用int取整
        let width = CGFloat(Int(self.width - itemMargin * 2) / 3)
        //  设置大小和间距,通过layout的size来改变布局显示
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        
    }

    
    // MARK:    UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ComposePictureViewCellIdentifier, forIndexPath: indexPath) as! CZComposePictureViewCell
//        cell.image = images[indexPath.item]
        //  如果cell 的item索引 等于数组的长度，说明是最后一个按钮了
        if indexPath.item == images.count {
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        
        cell.indexPath = indexPath
        cell.deleteImageClosure = { [weak self] (indexPath: NSIndexPath) in
            self?.images.removeAtIndex(indexPath.item)
            self?.reloadData()
            //  如果图片数组等于0，则隐藏
            if self?.images.count == 0 {
                self?.hidden = true
            }
            
        }
        
        return cell
        
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = images.count
        return (count == 0 || count == 9) ? count : count + 1
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //  如果点击的是最后一个item，则执行弹出图片选择视图操作
        if indexPath.item == images.count {
            addImageClosure?()
        }
        
    }
    
}

class CZComposePictureViewCell: UICollectionViewCell {
    var indexPath: NSIndexPath?
    //  点击删除按钮回调删除按钮操作
    var deleteImageClosure: ((indexPath: NSIndexPath)->())?

    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                //  设置高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
            } else {
                imageView.image = image
                //  高亮图片重用，重置成nil
                imageView.highlightedImage = nil
                
            }
            //  如果没有图片，隐藏删除按钮，有图片显示删除按钮
            deleteImageView.hidden = image == nil
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var imageView: UIImageView = UIImageView()
    private lazy var deleteImageView: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteImageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        deleteImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.top.equalTo(imageView)
        }
    }
 
    @objc private func deleteButtonClick() {
        if indexPath != nil {
            deleteImageClosure?(indexPath: indexPath!)
        }
        
    }
}
